package com.guoj.easyweb.interceptor;


import com.guoj.easyweb.common.exception.CustomException;
import com.guoj.easyweb.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("经过拦截器...." + request.getRequestURL());
//    	Login annotation;
//        if(handler instanceof HandlerMethod) {
//            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
//        }else{
//            return true;
//        }
//
//        if(annotation == null){
//            return true;
//        }

        //获取用户凭证，两种情况：1、header传过来；2、通过url传过来。
        String token = request.getHeader(jwtUtils.getHeader()) == null?request.getParameter(jwtUtils.getHeader()):request.getHeader(jwtUtils.getHeader());
		System.out.println("拦截器-token: " + token);

        // 凭证为空
        if(StringUtils.isBlank(token)){
        	log.error(jwtUtils.getHeader() + "不能为空");
            throw new CustomException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        // 凭证过期
        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
			log.error(jwtUtils.getHeader() + "失效，请重新登录");
            throw new CustomException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        // 设置userId到request里，后续根据userId，使用resolveArgument获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
